
import MainTableOperator from '../components/MainRowOperator';

import {snCreateUIDom, getAppPageConfig} from '../../../../hrpub/common/utils/utils';

import CommonAction from './common';
import {getBusinessInfo} from 'nc-lightapp-front';

let businessInfo = getBusinessInfo() || {};

let appConfig = getAppPageConfig();
let pcode = appConfig.pagecode;
let batchPageCode = pcode.substring(0, pcode.indexOf('n'));  // 拿到原始应用的appcode， 主要是解决复制应用出现的问题
const reqData = [{
    rqUrl: '/platform/templet/querypage.do',
    rqJson: `{\n  \"pagecode\": \"${appConfig.pagecode}\",\n  \"appcode\": \"${appConfig.appcode}\"\n}`,
    rqCode: 'template'
}, {
    rqUrl: '/platform/templet/querypage.do',
    rqJson: `{\n  \"pagecode\": \"${batchPageCode}batch\",\n  \"appcode\": \"${appConfig.appcode}\"\n}`,
    rqCode: 'batch_add'
}, {
    rqUrl: '/platform/appregister/queryallbtns.do',
    rqJson: `{\n  \"pagecode\": \"${appConfig.pagecode}\",\n  \"appcode\": \"${appConfig.appcode}\"\n}`,
    rqCode: 'button'
}, {
    rqUrl: '/platform/appregister/queryappcontext.do',
    rqJson: `{\n  \"appcode\": \"${appConfig.appcode}\"}`,
    rqCode: 'context'
}];

export default class MainAction extends CommonAction{
    constructor(comp) {
        super();
        this.comp = comp;
        if(comp.props.use){
            comp.props.use.form('card','card_batch', 'psninfo');
            comp.props.use.editTable('list','list_batch');
            comp.props.use.search('search','search_batch');
        }
    }

    appConfig = appConfig
    
    // 合并批量新增里的模版信息
    mergeTemplate = (res) => {
        let resource = this.deepCopy(res);
        let batchAdd = resource.batch_add;
        let template = {
            ...resource.template
        };

        template['list_batch'] = batchAdd['list_batch'];
        template['search_batch'] = batchAdd['search_batch'];
        template['card_batch'] = this.deepCopy(template['card']);
        template['card_batch'].code = 'card_batch';
        template['formrelation']['card_batch'] = this.deepCopy(template['formrelation']['card']);
        template['formrelation']['card'].map((item) => {
            this.comp.props.use.form(item)
        });
        Object.assign(template['gridrelation'], batchAdd['gridrelation']);

        return template;
    }

    // 获取多语
    getLanguage = () => {
        const {props} = this.comp;
        const {
            dispatch,
            MultiInit
        } = props;

        MultiInit.getMultiLang({
            moduleId: 'gx6008',
            domainName: 'hrtrn',
            callback: (json, status, init) => {
                dispatch({
                    type: 'emp/update',
                    payload: {
                        language: json
                    }
                });
            }
        });
    }

    //  获取内容页面高度，并且设置表格高度
    getMainTableHeight = () => {
        let content = document.querySelector('#app');

        if(window.getComputedStyle && content) {
            let height = window.getComputedStyle(content).height;

            height = height.replace('px', '');

            this.comp.props.dispatch({
                type: 'emp/update',
                payload: {
                    mainTableHeight: parseInt(height - 140),
                    pageHeight: height
                }
            });
        }
    }

    // 获取模版信息
    getTemplate = () => {
        const {props, action} = this.comp;
        const {
            meta, 
            button,
            dispatch
        } = props;
        
        snCreateUIDom(this.appConfig, reqData, (res) => {
            console.log(res);
            dispatch({
                type: 'emp/update',
                payload: {
                    context: res.context,
                    showOrgRefer: true
                }
            });
            let template = this.mergeTemplate(res);
            console.log(template);
            meta.setMeta(action.pTmp.processTemplate(template), this.processAfterGetTemplate);
            button.setButtons(res.button);
        });
    }

    // 当模版获取并设置完成之后的回调函数
    processAfterGetTemplate = () => {
        this.getUrlParam();
    }

    // 初始化
    didMount = () => {
        if (window.location.href.match('localhost:3006')) {
            window.location.hash = '#/ifr?page=201981519'
        }
        this.getTemplate();
        this.getLanguage();
        this.comp.action.btnAct.initPageButton();
        // 统一订阅事件
        this.subscribe();
    }

    // 获取url数据
    getUrlParam = async () => {
        const {props, action} = this.comp;
        const {getUrlParam, dispatch} = props;
        
        let scene = getUrlParam('scene');
        if (!scene && getUrlParam('status')) {
            scene = 'approvesce'
        }
        if(scene === 'approvesce') {
            dispatch({
                type: 'emp/update',
                payload: {
                    fromApprove: true,
                    orgValue:  {
                        refpk: businessInfo.groupId
                    }
                }
            });
        }
        else {
            await dispatch({
                type: 'emp/update',
                payload: {
                    page: 'main'
                }
            });
            setTimeout(() => {
                this.getMainTableHeight();
            }, 1);
           
            return;
        }

        let id = getUrlParam('id');
        let status = getUrlParam('status');
        let selectedRows = [{
            values: {
                pk_partmng: {
                    value: id
                }
            }
        }];

        if(status === 'browse') {
            action.formAct.toBrowsePage(selectedRows);
        }
        else {
            action.formAct.toEditPage(selectedRows);
        }
        
    }

    // 卸载
    willUnMount = () => {
        this.pubSub.unSubscribe('getMainTableData');
        this.pubSub.unSubscribe('fileManager');
        this.pubSub.unSubscribe('sendMessage');
    }

    // 事件订阅部分
    subscribe = () => {
        const {comp: {action}, pubSub} = this;
        pubSub.subscribe('getMainTableData', (...args) => {
            action.tableAct.getMainTableData(...args);
        });
        pubSub.subscribe('fileManager', (...args) => {
            this.fileManager(...args);
        });
        pubSub.subscribe('sendMessage', (...args) => {
            this.sendMessage(...args);
        });
    }

    // 确认查询
    toSearch = () => {
        this.comp.props.dispatch({
            type:'emp/update',
            payload: {
                hasSearched: true
            }
        });
        this.comp.action.tableAct.getMainTableData({hasSearched: true});
    }

    // 翻页
    turnPage = (page) => {
        const {props, action} = this.comp;
        const {
            emp,
            dispatch
        } = props;

        if(page === emp.pageInfo.pageIndex) {
            return;
        }

        let pageInfo = {
            ...emp.pageInfo,
            pageIndex: page
        }

        this.pubSub.publish('getMainTableData', {
            pageInfo: pageInfo
        });
    }

    // c改变每页显示条数
    changePageSize = (size) => {
        const {props, action} = this.comp;
        const {
            emp,
            dispatch
        } = props;

        if(size === emp.pageInfo.pageSize) {
            return;
        }

        let pageInfo = {
            ...emp.pageInfo,
            pageSize: size
        }

        this.pubSub.publish('getMainTableData', {
            pageInfo: pageInfo
        });
    }

    // 打印
    printTable = () => {
        const {props} = this.comp;
        const {emp, editTable, meta} = props;

        let tableWrapper = document.getElementById('mainTable');

        this.print(tableWrapper, {
            title: emp.language['gx6008-000247'], // 兼职办理
            maker: emp.language['gx6008-000068'], // 制作者
            date: emp.language['gx6008-000069'], // 制作日期
            beforeAppend: (data) => {

                data[0].map((item) => {
                    delete item[0];
                });
                data[1].map((item) => {
                    item.length = item.length - 1;
                });
                return data;
            }
        }, {
            data: editTable.getAllRows('list'),
            tableTmp: meta.getMeta()['list']
        });
    }

    // 输出
    outputTable = () => {
        const {
            props: {
                editTable,
                emp: {
                    language
                },
                meta
            }
        } = this.comp;
        let tableWrapper = document.getElementById('mainTable');
        let tableData = editTable.getAllData('list');

        this.exportHtml(tableWrapper, {
            fileName: language['gx6008-000247'] // '兼职办理'
        }, {
            meta: meta.getMeta()['list'],
            data: tableData.rows,
            showIndex: false
        });
    }

    // 福建管理
    fileManager = (selectedRows) => {

        const {props, action} = this.comp;
        const {emp, dispatch, editTable, meta} = props;

        let billId = selectedRows[0].values['pk_partmng'].value;

        dispatch({
            type: 'emp/update',
            payload: {
                fileManagerBillId: billId,
                fileManagerModalVisible: true
            }
        });
    }

    // 发送通知
    sendMessage = async (selectRows) => {
        const {action, props} = this.comp;
        const {dispatch, emp} = props;

        selectRows = this.comp.action.rowAct.getSelectedRows(selectRows);

        if(selectRows && selectRows.length > 0) {

            let postData = {
                billids: [],
                pk_org: emp.orgValue.refpk
            };
            selectRows.map((item) => {
                postData.billids.push(item.values['pk_partmng'].value);
            })

            let res = await dispatch({
                type: 'emp/sendMessage',
                payload: {
                    postData: postData
                }
            });

            if(res.success) {
                this.toast({
                    color: 'success',
                    content: res.data
                });
            }
        }
    }
}